﻿using System;
using System.Data;
using System.Drawing;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.IO;
using GandA.Web.UI.Controls.Util.Excel;

namespace GandA.Web.UI.Controls
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:GridView runat=server></{0}:GridView>")]
    [ToolboxBitmap(typeof(GridView), "GridView.png")]
    public class GridView : System.Web.UI.WebControls.GridView
    {
        #region Propiedades
        [Bindable(true)]
        [Category("Style")]
        [DefaultValue("")]
        [Localizable(true)]
        public Color MouseOverColor
        {
            get { return ViewState["_mouseOverColor"] == null ? Color.FromArgb(56, 174, 224) : (Color)ViewState["_mouseOverColor"]; }
            set { ViewState["_mouseOverColor"] = value; }
        }

        [Bindable(true)]
        [Category("Style")]
        [DefaultValue("")]
        [Localizable(true)]
        public Color TextOverColor
        {
            get { return ViewState["_textOverColor"] == null ? Color.White : (Color)ViewState["_textOverColor"]; }
            set { ViewState["_textOverColor"] = value; }
        }

        [Bindable(true)]
        [Category("Style")]
        [DefaultValue("")]
        [Localizable(true)]
        public Color SelectedRowColor
        {
            get { return ViewState["_selectedRowColor"] == null ? Color.FromArgb(170, 222, 243) : (Color)ViewState["_selectedRowColor"]; }
            set { ViewState["_selectedRowColor"] = value; }
        }

        [Bindable(true)]
        [Category("Style")]
        [DefaultValue("")]
        [Localizable(true)]
        public Color SelectedRowTextColor
        {
            get { return ViewState["_selectedRowTextColor"] == null ? Color.Black : (Color)ViewState["_selectedRowTextColor"]; }
            set { ViewState["_selectedRowTextColor"] = value; }
        }

        [Bindable(true)]
        [Category("Behavior")]
        [DefaultValue("")]
        [Localizable(true)]
        public bool AutoPostBack
        {
            get
            {
                return ViewState["_AutoPostBack"] == null ? false : (bool)ViewState["_AutoPostBack"];
            }
            set
            {
                ViewState["_AutoPostBack"] = value;
            }
        }

        [Bindable(true)]
        [Category("Layout")]
        [DefaultValue(false)]
        [Localizable(true)]
        public bool AllowScroll
        {
            get
            {
                return ViewState["_AllowScroll"] == null ? false : (bool)ViewState["_AllowScroll"];
            }
            set
            {
                ViewState["_AllowScroll"] = value;
                this.ShowHeader = false;
            }
        }

        //[Bindable(true)]
        //[Category("Data")]
        //[DefaultValue(null)]
        //[Localizable(true)]
        //public override object DataSource
        //{
        //    get
        //    {
        //        return ViewState["_ds"];
        //    }
        //    set
        //    {
        //        ViewState["_ds"] = value;
        //    }
        //}
        #endregion

        protected override void OnPreRender(EventArgs e)
        {
            bool linkIncluded = false;
            foreach (Control c in Page.Header.Controls)
            {
                if (c.ID == "StyleControls")
                {
                    linkIncluded = true;
                }
            }
            if (!linkIncluded)
            {
                HtmlGenericControl csslink = new HtmlGenericControl("link");
                csslink.ID = "StyleControls";
                csslink.Attributes.Add("href", Page.ClientScript.GetWebResourceUrl(this.GetType(), "GandA.Web.UI.Controls.Controls.css"));
                csslink.Attributes.Add("type", "text/css");
                csslink.Attributes.Add("rel", "stylesheet");
                Page.Header.Controls.Add(csslink);
            }

            //this.PagerSettings.FirstPageImageUrl = ResolveClientUrl("../App_Themes/" + Page.Theme + "/Images/btnQt.png");
            //this.PagerSettings.LastPageImageUrl = ResolveClientUrl("../App_Themes/" + Page.Theme + "/Images/btnAt.png");
            //this.PagerSettings.NextPageImageUrl = ResolveClientUrl("../App_Themes/" + Page.Theme + "/Images/btnA.png");
            //this.PagerSettings.PreviousPageImageUrl = ResolveClientUrl("../App_Themes/" + Page.Theme + "/Images/btnQ.png");
            this.PagerSettings.FirstPageText = "Primero";
            this.PagerSettings.LastPageText = "Último";
            this.PagerSettings.NextPageText = "Siguiente";
            this.PagerSettings.PreviousPageText = "Anterior";
            base.OnPreRender(e);

            string resourceName = "GandA.Web.UI.Controls.GridView.js";
            ClientScriptManager cs;
            if (this.Page == null)
                cs = this.Parent.Page.ClientScript;
            else
                cs = this.Page.ClientScript;
            cs.RegisterClientScriptResource(typeof(GandA.Web.UI.Controls.GridView), resourceName);
            cs.RegisterClientScriptBlock(typeof(GandA.Web.UI.Controls.GridView), "", "var gHeader='" + this.ID + "_gHeader';" + "var bodyTable='" + this.ID + "_bodyTable'", true);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            string csHeader = string.Empty;
            ClientScriptManager cs;
            if (this.Page == null)
                cs = this.Parent.Page.ClientScript;
            else
                cs = this.Page.ClientScript;
            //cs.RegisterStartupScript(typeof(Page), "HotKeys", "if (typeof ($) != 'undefined') $(document).bind('keydown', HotKeysGrid);", true);
            if (AllowScroll)
            {
                this.ShowHeader = false;
                csHeader = this.HeaderStyle.CssClass;
                this.HeaderStyle.CssClass = "gridViewHiddenHeader";
            }

            if (AutoPostBack)
            {
                //const string onMouseOverStyle = "this.className='GridViewMouseOver';";
                //const string onMouseOutStyle = "this.className='{0}';";

                foreach (GridViewRow row in this.Rows)
                {
                    //row.Attributes["onmouseover"] = onMouseOverStyle;
                    //row.Attributes["onmouseout"] = String.Format(
                    //        onMouseOutStyle,
                    //        GetRowStyleCssClass(row.RowState));
                    row.Attributes["onclick"] = cs.GetPostBackClientHyperlink(
                            this,
                            String.Concat("Select$", row.RowIndex),
                            true);
                }
            }

            foreach (GridViewRow row in this.Rows)
            {
                if (AllowScroll)
                {
                    foreach (TableCell col in row.Cells)
                    {
                        col.Style.Add("word-wrap", "break-word");
                        col.Style.Add("border-color", "#BDBDBD");
                        col.Style.Add("padding-left", "2px");
                        col.Style.Add("padding-right", "2px");
                    }
                }
            }

            foreach (GridViewRow row in this.Rows)
            {
                row.Attributes.Add("OriginalClassName", GetRowStyleCssClass(row.RowState));
            }

            if (AllowScroll)
            {
                Unit widthGrid = this.Width;
                string unitg = string.Empty;
                if (widthGrid.ToString().Contains("%"))
                    unitg = "%";
                else
                    unitg = "px";
                if (string.IsNullOrEmpty(csHeader))
                    csHeader = "GridViewHeader";

                if (!string.IsNullOrEmpty(this.Caption.Trim()))
                {
                    writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ID + "_gCaption");
                    writer.AddAttribute(HtmlTextWriterAttribute.Class, csHeader);
                    switch (this.CaptionAlign)
                    {
                        case TableCaptionAlign.Bottom:
                            writer.AddAttribute(HtmlTextWriterAttribute.Style,
                                       "width: " + (widthGrid.Value).ToString() + unitg +
                                       ";border:1px; border-bottom:0px; border-style:solid;padding-top:2px;padding-bottom:2px;overflow:hidden;vertical-align:bottom;");
                            break;
                        case TableCaptionAlign.Left:
                            writer.AddAttribute(HtmlTextWriterAttribute.Style,
                                       "width: " + (widthGrid.Value).ToString() + unitg +
                                       ";border:1px; border-bottom:0px; border-style:solid;padding-top:2px;padding-bottom:2px;overflow:hidden;text-align:left;");
                            break;
                        case TableCaptionAlign.NotSet:
                            writer.AddAttribute(HtmlTextWriterAttribute.Style,
                                       "width: " + (widthGrid.Value).ToString() + unitg +
                                       ";border:1px; border-bottom:0px; border-style:solid;padding-top:2px;padding-bottom:2px;overflow:hidden;text-align:center;");
                            break;
                        case TableCaptionAlign.Right:
                            writer.AddAttribute(HtmlTextWriterAttribute.Style,
                                       "width: " + (widthGrid.Value).ToString() + unitg +
                                       ";border:1px; border-bottom:0px; border-style:solid;padding-top:2px;padding-bottom:2px;overflow:hidden;text-align:Right;");
                            break;
                        case TableCaptionAlign.Top:
                            writer.AddAttribute(HtmlTextWriterAttribute.Style,
                                       "width: " + (widthGrid.Value).ToString() + unitg +
                                       ";border:1px; border-bottom:0px; border-style:solid;padding-top:2px;padding-bottom:2px;overflow:hidden;vertical-align:top;");
                            break;
                    }

                    writer.RenderBeginTag(HtmlTextWriterTag.Div);
                    writer.Write(this.Caption);
                    this.Caption = "";
                    writer.RenderEndTag();
                }
                writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ID + "_gHeader");
                writer.AddAttribute(HtmlTextWriterAttribute.Style,
                                    "width: " + (widthGrid.Value).ToString() + unitg +
                                    ";border:1px; border-style:solid;padding-top:2px;padding-bottom:2px;overflow:hidden;");
                
                writer.AddAttribute(HtmlTextWriterAttribute.Class, csHeader);
                writer.RenderBeginTag(HtmlTextWriterTag.Div);
                // Table
                writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ID + "_headerTblVisible");
                string unit = "";
                double width = getWidth(ref unit);
                this.Width = Unit.Pixel((int) width);
                writer.AddAttribute(HtmlTextWriterAttribute.Style,
                                    "width: " + (width == 0 ? "200px" : ((width + 34).ToString() + unit)) +
                                    "; border-top-width:0px;border-right-width:1px;border-bottom-width:0px;border-left-width:0;table-layout: fixed;padding-left:1px;padding-right:1px;");
                writer.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0");
                writer.AddAttribute(HtmlTextWriterAttribute.Rules, "all");
                writer.RenderBeginTag(HtmlTextWriterTag.Table);

                //bool ban4 = false;
                string unit4 = string.Empty;
                writer.RenderBeginTag(HtmlTextWriterTag.Tr); //<tr>
                int colcount = Columns.Count;
                int colnum = 0;
                foreach (DataControlField col in this.Columns)
                {
                    if (col.Visible)
                    {
                        if (colcount-1 == colnum)
                        {
                            if (col.ItemStyle.Width.ToString().Contains("%"))
                                unit4 = "%";
                            else
                                unit4 = "px";

                            writer.AddAttribute(HtmlTextWriterAttribute.Style,
                                                "word-wrap:break-word;width:" + (col.ItemStyle.Width.Value).ToString() + unit4 +
                                                ";border-color:#BDBDBD;padding-left:2px;padding-right:2px;");
                        }
                        else
                        {
                            writer.AddAttribute(HtmlTextWriterAttribute.Style,
                                                "word-wrap:break-word;width:" + col.ItemStyle.Width.ToString() +
                                                ";border-color:#BDBDBD;padding-left:2px;padding-right:2px;");
                        }
                        writer.RenderBeginTag(HtmlTextWriterTag.Td);
                        if (this.AllowSorting)
                            writer.WriteFullBeginTag("a class='gridViewSortHeader' href=\"" + "javascript:__doPostBack('" + this.UniqueID +
                                                     "','Sort$" + col.ToString() + "')\"" + ">" + col.HeaderText + "</a");
                        else
                            writer.Write(col.HeaderText);
                        writer.RenderEndTag();
                    }

                    colnum++;
                }

                writer.RenderEndTag(); //<tr/>
                writer.RenderEndTag();
                // Fin Table

                writer.RenderEndTag();
                // Fin Div Header

                //writer.RenderBeginTag(HtmlTextWriterTag.Div);
                writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ID + "_bodyTable", false);
                //writer.AddAttribute(HtmlTextWriterAttribute.Style, "width: " + (widthGrid.Value + 17).ToString() + "px; height:" + this.Height.ToString() +";border:1px; overflow-x: hidden; overflow-y: auto;");
                writer.AddAttribute(HtmlTextWriterAttribute.Style,
                                    "width: " + (widthGrid.Value).ToString() + unitg + "; height:" + this.Height.ToString() +
                                    ";border-top-width:0px;border-bottom-width:0px;border-left-width:1px;border-right-width:1px; border-style:solid;overflow-x: hidden; overflow-y: scroll;");
                this.Height = new Unit();

                this.Style.Add("width", (width + 34).ToString() + "px");
                this.Style.Add("table-layout", "fixed");
                //this.Attributes.Add("border", "0");
                this.Style.Add("border-top-width", "0px");
                this.Style.Add("border-right-width", "1px");
                this.Style.Add("border-bottom-width", "1px");
                this.Style.Add("border-left-width", "1px");
                this.Style.Add("border-color", "#BDBDBD");
                this.Style.Add("padding-left", "1px");
                this.Style.Add("padding-right", "1px");
                this.PagerStyle.CssClass = "gridViewHiddenPager";
                //this.PagerSettings.Visible = false;
                base.Render(writer);
                writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ID + "_footerScroll", false);
                writer.AddAttribute(HtmlTextWriterAttribute.Style,
                                    "width: " + (widthGrid.Value).ToString() + unitg +
                                    "; overflow-x:" + (Convert.ToDouble(widthGrid.Value) >= width ? "none" : "auto") +
                                    "; display:" + (Convert.ToDouble(widthGrid.Value) >= width ? "none" : "block") +
                                    "; height:17px;border-width:0px;border-right-width: 1px;border-left-width: 1px;border-bottom-width: 1px; border-style:solid");
                writer.AddAttribute("onscroll", "scrollHorizontal(this);");
                writer.RenderBeginTag(HtmlTextWriterTag.Div); //div

                writer.AddAttribute(HtmlTextWriterAttribute.Style,
                                    "width:" + (width == 0 ? "200px" : ((width + 18).ToString() + unit)) +
                                    ";border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-collapse: collapse; table-layout: fixed;visibility:hidden;padding-left:1px;padding-right:1px;");
                writer.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0");
                writer.AddAttribute(HtmlTextWriterAttribute.Rules, "all");
                writer.RenderBeginTag(HtmlTextWriterTag.Table); //table
                //writer.AddAttribute(HtmlTextWriterAttribute.Style, "height: 1px;");
                writer.RenderBeginTag(HtmlTextWriterTag.Tr); //<tr>
                bool ban = false;
                string unit2 = string.Empty;
                foreach (DataControlField col in this.Columns)
                {
                    if (col.Visible)
                    {
                        if (col.ItemStyle.Width.Value > 17 && ban == false)
                        {
                            ban = true;
                            if (col.ItemStyle.Width.ToString().Contains("%"))
                                unit2 = "%";
                            else
                                unit2 = "px";

                            writer.AddAttribute(HtmlTextWriterAttribute.Style,
                                             "word-wrap:break-word;width:" + (col.ItemStyle.Width.Value-17).ToString() +
                                             ";padding-left:2px;padding-right:2px;");
                        }
                        else
                        {
                            writer.AddAttribute(HtmlTextWriterAttribute.Style,
                                                "word-wrap:break-word;width:" + col.ItemStyle.Width.ToString() +
                                                ";padding-left:2px;padding-right:2px;");
                        }
                        writer.RenderBeginTag(HtmlTextWriterTag.Td);
                        writer.Write(col.HeaderText);
                        writer.RenderEndTag(); //td
                    }
                }
                writer.RenderEndTag(); //<tr/>
                writer.RenderEndTag(); //table
                writer.RenderEndTag(); //div

                if (this.AllowPaging)
                {
                    writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ID + "_footerPag", false);
                    writer.AddAttribute(HtmlTextWriterAttribute.Class, "gridViewFooterPag", false);
                    writer.AddAttribute(HtmlTextWriterAttribute.Style, "width: " + (widthGrid.Value).ToString() + unitg +
                                        ";text-aling:right");
                    writer.RenderBeginTag(HtmlTextWriterTag.Div); //div

                    if (this.PageIndex + 1 != this.PageCount && this.PageCount > 0)
                    {
                        writer.AddStyleAttribute(HtmlTextWriterStyle.Padding, "4px 2px 2px 2px");
                        writer.AddStyleAttribute("float", "right;");
                        writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ID + "_btnLast");
                        writer.RenderBeginTag(HtmlTextWriterTag.Div);
                        writer.AddAttribute(HtmlTextWriterAttribute.Onclick, "javascript:__doPostBack('" + this.UniqueID + "','Page$Last')", false);
                        writer.AddStyleAttribute(HtmlTextWriterStyle.Cursor, "Pointer");
                        writer.RenderBeginTag(HtmlTextWriterTag.A);
                        writer.WriteFullBeginTag("img alt='Último' title='Último' class='gridViewPagLast' /");
                        writer.RenderEndTag(); //a
                        writer.RenderEndTag(); //div

                        writer.AddStyleAttribute(HtmlTextWriterStyle.Padding, "4px 2px 2px 2px");
                        writer.AddStyleAttribute("float", "right;");
                        writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ID + "_btnNext");
                        writer.RenderBeginTag(HtmlTextWriterTag.Div);
                        writer.AddAttribute(HtmlTextWriterAttribute.Onclick, "javascript:__doPostBack('" + this.UniqueID + "','Page$Next')", false);
                        writer.AddStyleAttribute(HtmlTextWriterStyle.Cursor, "Pointer");
                        writer.RenderBeginTag(HtmlTextWriterTag.A);
                        writer.WriteFullBeginTag("img alt='Siguiente' title='Siguiente' class='gridViewPagSig' /");
                        writer.RenderEndTag(); //a
                        writer.RenderEndTag(); //div
                    }

                    writer.AddStyleAttribute(HtmlTextWriterStyle.Padding, "2px 2px 2px 2px");
                    writer.AddStyleAttribute("float", "right;");
                    writer.RenderBeginTag(HtmlTextWriterTag.Div);
                    if (this.PageCount > 0)
                        writer.WriteEncodedText("Pag. " + (this.PageIndex + 1).ToString() + " de " + this.PageCount);
                    else
                        writer.WriteEncodedText("Sin Páginas");
                    writer.RenderEndTag(); //div

                    if (this.PageIndex > 0)
                    {
                        writer.AddStyleAttribute(HtmlTextWriterStyle.Padding, "4px 2px 2px 2px");
                        writer.AddStyleAttribute("float", "right;");
                        writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ID + "_btnPrev");
                        writer.RenderBeginTag(HtmlTextWriterTag.Div);
                        writer.AddAttribute(HtmlTextWriterAttribute.Onclick, "javascript:__doPostBack('" + this.UniqueID + "','Page$Prev')", false);
                        writer.AddStyleAttribute(HtmlTextWriterStyle.Cursor, "Pointer");
                        writer.RenderBeginTag(HtmlTextWriterTag.A);
                        writer.WriteFullBeginTag("img alt='Anterior' title='Anterior' class='gridViewPagAnt' /");
                        writer.RenderEndTag(); //a
                        writer.RenderEndTag(); //div

                        writer.AddStyleAttribute(HtmlTextWriterStyle.Padding, "4px 2px 2px 2px");
                        writer.AddStyleAttribute("float", "right;");
                        writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ID + "_btnFirst");
                        writer.RenderBeginTag(HtmlTextWriterTag.Div);
                        writer.AddAttribute(HtmlTextWriterAttribute.Onclick, "javascript:__doPostBack('" + this.UniqueID + "','Page$First')", false);
                        writer.AddStyleAttribute(HtmlTextWriterStyle.Cursor, "Pointer");
                        writer.RenderBeginTag(HtmlTextWriterTag.A);
                        writer.WriteFullBeginTag("img alt='Primero' title='Primero' class='gridViewPagFirst' /");
                        writer.RenderEndTag(); //a
                        writer.RenderEndTag(); //div
                    }

                    writer.RenderEndTag(); //div
                }
            }
            else
            {
                base.Render(writer);
            }
        }
        
        protected override void OnPageIndexChanged(EventArgs e)
        {
 	        base.OnPageIndexChanged(e);
        }
    
        protected override void OnRowCreated(GridViewRowEventArgs e)
        {
            base.OnRowCreated(e);
            GridViewRow row = e.Row;
            Color bgColor = Color.Empty;
            Color color = Color.Empty;
            const string onMouseOverStyle = "GridViewMouseOver";
            const string onMouseOutStyle = "this.className='{0}';";

            if (row.RowIndex % 2 == 0)
            {
                bgColor = (this.RowStyle.BackColor == Color.Empty) ? Color.White : this.RowStyle.BackColor;
                color = (this.RowStyle.ForeColor == Color.Empty) ? Color.Black : this.RowStyle.ForeColor;
            }
            else
            {
                bgColor = (this.AlternatingRowStyle.BackColor == Color.Empty) ? Color.White : this.AlternatingRowStyle.BackColor;
                color = (this.AlternatingRowStyle.ForeColor == Color.Empty) ? Color.Black : this.AlternatingRowStyle.ForeColor;
            }

            if (row.RowType == DataControlRowType.DataRow)
            {
                row.Attributes.Add("onmousedown", String.Format("MouseDown(this,'{0}')",
                        this.SelectedRowStyle.CssClass));
                row.Attributes.Add("onmouseover", String.Format("MouseEnter(this,'{0}')",
                    onMouseOverStyle));
                row.Attributes.Add("onmouseout", "MouseLeave(this)");
                row.Attributes.Add("Selected", "false");
            }
        }

        protected override void OnSelectedIndexChanging(GridViewSelectEventArgs e)
        {
            base.OnSelectedIndexChanging(e);
            if (!e.Cancel)
            {
                ClearSelection();
                this.Rows[e.NewSelectedIndex].Attributes.Add("Selected", this.Rows[e.NewSelectedIndex].Attributes["Selected"] == "true" ? "false" : "true");
            }
        }
        
        private void ClearSelection()
        {
            foreach (GridViewRow row in this.Rows)
            {
                row.Attributes.Add("Selected", "false");
            }   
        }
        
        private string GetRowStyleCssClass(DataControlRowState state)
        {
            if ((state & DataControlRowState.Edit) > 0)
            {
                return this.EditRowStyle.CssClass;
            }
            else if ((state & DataControlRowState.Selected) > 0)
            {
                return this.SelectedRowStyle.CssClass;
            }
            else if ((state & DataControlRowState.Alternate) > 0)
            {
                return this.AlternatingRowStyle.CssClass;
            }
            else
            {
                return this.RowStyle.CssClass;
            }
        }

        private double getWidth(ref string unit)
        {
            double width = 0;
            foreach (DataControlField col in this.Columns)
            {
                if (col.Visible)
                {
                    width = width + col.ItemStyle.Width.Value;
                    if (col.ItemStyle.Width.ToString().Contains("%"))
                        unit = "%";
                    else
                        unit = "px";
                }
            }

            return width;
        }
        
        public void ToExportExcel(string sheetName)
        {
            XLWorkbook wb = new XLWorkbook();
            var ws = wb.Worksheets.Add(sheetName);
            ws.Cell(2, 1).InsertTable(getDataTable());
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            HttpContext.Current.Response.AddHeader("content-disposition", String.Format(@"attachment;filename={0}.xlsx",sheetName.Replace(" ","_")));

            using (MemoryStream memoryStream = new MemoryStream())
            {
                wb.SaveAs(memoryStream);
                memoryStream.WriteTo(HttpContext.Current.Response.OutputStream);
                memoryStream.Close();
            }

            HttpContext.Current.Response.End();
        }

        private DataTable getDataTable()
        {
            DataTable dt = new DataTable();

            // add the columns to the datatable            
            if (HeaderRow != null)
            {

                for (int i = 0; i < Columns.Count; i++)
                {
                    dt.Columns.Add(Columns[i].HeaderText);
                }
            }

            //  add each of the data rows to the table
            foreach (GridViewRow row in Rows)
            {
                DataRow dr;
                dr = dt.NewRow();

                for (int i = 0; i < row.Cells.Count; i++)
                {
                    dr[i] = row.Cells[i].Text.Replace("&nbsp;", "");
                }
                dt.Rows.Add(dr);
            }

            //  add the footer row to the table
            if (FooterRow != null)
            {
                DataRow dr;
                dr = dt.NewRow();

                for (int i = 0; i < FooterRow.Cells.Count; i++)
                {
                    dr[i] = FooterRow.Cells[i].Text.Replace("&nbsp;", "");
                }

                dt.Rows.Add(dr);
            }

            // Remove columns invisibles
            foreach (DataControlField col in Columns)
            {
                if (!col.Visible)
                {
                    int numCol = dt.Columns.IndexOf(col.HeaderText);
                    if (numCol >= 0)
                    {
                        dt.Columns.RemoveAt(numCol);
                    }
                }
            }

            return dt;
        }

        public bool ToExportCsv()
        {
            try
            {
                if (this.Rows.Count > 0)
                {
                    Page.Response.Clear();
                    Page.Response.Buffer = true;
                    Page.Response.AddHeader("content-disposition", "attachment;filename=" + this.ID + ".csv");
                    Page.Response.Charset = "";
                    Page.Response.ContentType = "application/text";
                    //this.AllowPaging = false;
                    //Page.DataBind();

                    StringBuilder sb = new StringBuilder();
                    for (int k = 0; k < this.Columns.Count; k++)
                    {
                        if (this.Columns[k].Visible && this.Columns[k].HeaderText != "Acción")
                        {
                            //add separator
                            sb.Append(HttpUtility.HtmlDecode(this.Columns[k].HeaderText) + ',');
                        }
                    }
                    //append new line
                    sb.Append("\r\n");
                    for (int i = 0; i < this.Rows.Count; i++)
                    {
                        for (int k = 0; k < this.Columns.Count; k++)
                        {
                            if (this.Columns[k].Visible && this.Columns[k].HeaderText != "Acción")
                            {
                                //add separator
                                sb.Append(this.Rows[i].Cells[k].Text == "&nbsp;" ? "," : HttpUtility.HtmlDecode(this.Rows[i].Cells[k].Text) + ',');
                            }
                        }
                        //append new line
                        sb.Append("\r\n");
                    }

                    Page.Response.Charset = "UTF-8";
                    Page.Response.ContentEncoding = System.Text.Encoding.Unicode;
                    Page.Response.Output.Write(sb.ToString());
                    Page.Response.Flush();
                    //HttpContext.Current.ApplicationInstance.CompleteRequest();
                    Page.Response.End();
                }
            }
            catch (Exception ex)
            {
                return false;
            }

            return true;
        }
    }
}
